package com.cskaoyan.wordmemorize.controller.admin;


import com.cskaoyan.wordmemorize.auth.SaAdminCheckPermission;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.constant.ResultCodeEnum;
import com.cskaoyan.wordmemorize.common.exception.ExcelParseException;
import com.cskaoyan.wordmemorize.common.result.Result;

import com.cskaoyan.wordmemorize.dto.admin.DeleteVocFileOperateDTO;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.VocChapBookDTO;
import com.cskaoyan.wordmemorize.dto.admin.VocDTO;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocCommand;
import com.cskaoyan.wordmemorize.request.VocPageRequest;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import com.cskaoyan.wordmemorize.service.VocService;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/admin/voc")
public class AdminVocController {

    @Autowired
    VocService vocService;

    @Autowired
    FileUploadService fileUploadService;

    @SaAdminCheckPermission("admin:voc:add")
    @PostMapping("")
    public Result addVoc(@RequestBody VocCommand vocCommand){
        vocService.addVoc(vocCommand);
        return Result.ok();
    }

    @SaAdminCheckPermission("admin:voc:update")
    @PutMapping("")
    public Result updateVoc(@RequestBody VocCommand vocCommand){
        vocService.updateVoc(vocCommand);
        return Result.ok();
    }
    @SaAdminCheckPermission("admin:voc:delete")
    @DeleteMapping("/{vocId}")
    public Result deleteVoc(@PathVariable Long vocId){
        vocService.deleteVocabulary(vocId);
        return Result.ok();
    }
    @SaAdminCheckPermission("admin:voc:batchdelete")
    @DeleteMapping("")
    public Result deleteVocs(@RequestBody BatchDeleteCommand batchDeleteCommand){
        vocService.deleteVocabularies(batchDeleteCommand);
        return Result.ok();
    }
    @SaAdminCheckPermission("admin:voc:search")
    @GetMapping("/list")
    public Result<PageDTO<VocDTO>> getVocList(VocPageRequest vocPageRequest) {
        PageDTO<VocDTO> vocDTOPageDTO = vocService.getVocabularies(vocPageRequest);
        return Result.ok(vocDTOPageDTO);
    }
    @GetMapping("/relations/{vocId}")
    // 指定单词的单词-章节-书籍关系列表
    public Result<List<VocChapBookDTO>> getVocChapBookRelations(@PathVariable("vocId") Long vocId){
        List<VocChapBookDTO> vocChapBookDTOS = vocService.getVocRelations(vocId);
        return Result.ok(vocChapBookDTOS);
    }
    @DeleteMapping("/relation/{id}")
    // 删除指定单词的单词-章节-书籍关系
    public Result deleteVocChapBookRelation(@PathVariable("id") Long id){
        vocService.deleteVocRelation(id);
        return Result.ok();
    }
    @DeleteMapping("/interpretation/{id}")
    // 删除指定单词的解释关系
    public Result deleteVocInterpretationRelation(@PathVariable("id") Long id){
        vocService.deleteInterpretation(id);
        return Result.ok();
    }

    @DeleteMapping("/example/{id}")
    // 删除指定单词的例句关系
    public Result deleteVocExampleRelation(@PathVariable("id") Long id){
        vocService.deleteExample(id);
        return Result.ok();
    }
    @PostMapping("/file")
    public Result<String> addVocFileAudio(@RequestBody MultipartFile file) throws IOException {
        String uploadFileURL = fileUploadService.upload(file);
        return Result.ok(uploadFileURL);
    }

    @DeleteMapping("/file/{type}/{id}")
    public Result deleteVocFile(@PathVariable("id") Long id,
                                @PathVariable("type") String type,
                                @RequestParam("name") String name){
        DeleteVocFileOperateDTO deleteVocFileOperateDTO = vocService.deleteFile(id, type, name);
        if(deleteVocFileOperateDTO == null){
            return Result.fail();
        }else {
            return Result.ok();
        }
    }

    @GetMapping("template")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        // 使用ClassPathResource读取资源文件

        ClassPathResource resource;
        resource = new ClassPathResource("templates/单词上传模版.xlsx");

        // 检查文件是否存在
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        InputStream inputStream = resource.getInputStream();
        byte[] fileBytes = IOUtils.toByteArray(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",
                URLEncoder.encode(resource.getFilename(), "UTF-8"));

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }

    @SaAdminCheckPermission("admin:voc:excel:upload")
    @PostMapping("excel")
    public Result addVocExcel(@RequestParam("vocExcel") MultipartFile file) throws IOException{
        Long employeeId = StpKit.ADMIN.getLoginIdAsLong();
        // 调用该方法完成Excel上传单词功能
        vocService.addVocExcel(file, employeeId);
        return Result.ok();
    }

    @PostMapping("/excel/validate")
    public Result vocExcelVerify(@RequestParam("vocExcel") MultipartFile file) throws IOException {
        // 在该service方法中完成Excel文件内容的读取
        vocService.vocExcelValidate(file);
        return Result.ok();
    }
}
